#!/bin/bash

is_valid_hdc1080()
{
    local I2C_BUS=$1
    local DEV_ADDR=$2

    MFR_ID=$(i2ctransfer -y -f "${I2C_BUS}" w1@"${DEV_ADDR}" 0xfe r2)
    if [ "$MFR_ID" != "0x54 0x49" ]; then
        return 1;
    fi

    DEV_ID=$(i2ctransfer -y -f "${I2C_BUS}" w1@"${DEV_ADDR}" 0xff r2)
    if [ "$DEV_ID" != "0x10 0x50" ]; then
        return 1;
    fi

    return 0;
}

set_frontpanel_model()
{
    busctl set-property xyz.openbmc_project.Settings /xyz/openbmc_project/inventory/system/chassis0/frontpanel xyz.openbmc_project.Inventory.Decorator.Asset Model s "Bletchley_FPB_${1}"
}

I2C_BUS=10
DEV_ADDR=0x40

VIRT_SNR_CONF="/var/lib/phosphor-virtual-sensor/virtual_sensor_config.json"
HDC1080_VIRT_SNR_CONF="/usr/share/phosphor-virtual-sensor/virtual_sensor_config_hdc1080.json"
SI7021_VIRT_SNR_CONF="/usr/share/phosphor-virtual-sensor/virtual_sensor_config_si7021.json"

# Check chip type
if is_valid_hdc1080 "$I2C_BUS" "$DEV_ADDR"; then
    CHIP_TYPE="HDC1080"
else
    CHIP_TYPE="SI7021"
fi

# Set Frontpanel board model
set_frontpanel_model "$CHIP_TYPE"

# Setup virtual_sensor_config.json for phosphor-virtual-sensor
case "$CHIP_TYPE" in
"HDC1080")
    REQUIRED_CONF_PATH="$HDC1080_VIRT_SNR_CONF"
    ;;
"SI7021")
    REQUIRED_CONF_PATH="$SI7021_VIRT_SNR_CONF"
    ;;
*)
    REQUIRED_CONF_PATH="$HDC1080_VIRT_SNR_CONF"
    ;;
esac

if [ ! -d "$(dirname $VIRT_SNR_CONF)" ]; then
    mkdir -p "$(dirname $VIRT_SNR_CONF)"
fi

if [ ! -e "$VIRT_SNR_CONF" ]; then
    ln -s "$REQUIRED_CONF_PATH" "$VIRT_SNR_CONF"
else
    REAL_CONF_PATH="$(realpath $VIRT_SNR_CONF)"
    if [ "$REAL_CONF_PATH" != "$REQUIRED_CONF_PATH" ]; then
        rm "$VIRT_SNR_CONF"
        ln -s "$REQUIRED_CONF_PATH" "$VIRT_SNR_CONF"
    fi
fi
